//
//  homeViewController.m
//  壳牌喜力促销积分商城
//
//  Created by xrd on 15/3/15.
//  Copyright (c) 2015年 xrd. All rights reserved.
//

#import "homeViewController.h"
#import "TuijianModel.h"
#import "TuijianView.h"
//#import "FLTableViewController.h"
#import "WebViewController.h"
#import "AFNetworking.h"
#import "TuijianModel.h"
#define kTuiJianMargin 10   // 推荐商品的间隔
#define kTuijianCol 2    // 推荐商品要几列
#define  ImageCount 5
@interface homeViewController ()<TuijianViewDelegate,UISearchBarDelegate, UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIPageControl *pageControel;
@property (weak, nonatomic) IBOutlet UIScrollView *UpScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
// 搜索控件
@property (nonatomic, strong) UISearchBar *searchBar;
// 展示数据的数组
@property (nonatomic, strong) NSArray *dataList;


//存储上边的 UPscrollView的图片
@property (nonatomic,strong) NSMutableArray *images;




@end

@implementation homeViewController
- (NSArray *)dataList
{
    
    
    if (_dataList == nil) {
        NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"tuijian" ofType:@"plist"]];
        NSMutableArray *arrM = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            TuijianModel *model = [TuijianModel tuijianWithDictionary:dict];
            [arrM addObject:model];
        }
        _dataList = arrM;
    }
    return _dataList;
}
- (void)viewDidLoad {
    // 1. 添加搜索框
    [self setupSearchView];
    //2.添加左右滑动ScorllView
    [self  setupScorllView];
    
    
   // 向推荐商品 里面添加子控件
    [self addSubViewToScrollView];
    
//    [self getJSON];
    /*
//  推荐商品  http://192.168.1.103:8080/ShellService/forStage/ForeStageAction_getGiftOfRecommend.action
    
//   NSString *string =[NSString stringWithFormat: @" http://192.168.1.200:8080/ShellService/forStage/ForeStageAction_getGiftOfRecommend.action"];
//
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];

//     params[@"access_token"] = [HMAccountTool account].access_token;

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

        NSDictionary *parameters = @{@"username":@"zhangsan",@"password":@"zhangsan"};
    */
    
//    NSDictionary * parameters = [[NSDictionary alloc] initWithDictionary:[];
    /*
    [manager POST:@"http://192.168.1.200:8080/ShellService/forStage/ForeStageAction_getGiftOfRecommend.action"parameters:parameters
     
          success:^(AFHTTPRequestOperation *operation,id responseObject) {
              
              NSLog(@"Success: %@", responseObject);
              
          }failure:^(AFHTTPRequestOperation *operation,NSError *error) {
              
              NSLog(@"Error: %@", error);
              
          }];
    */
    
    [self openURL];
}
- (void)getJSON {
    //1.请求管理器
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    //2.发起请求
    [manager GET:Request_URL parameters:nil success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"responseObjectresponseObjectresponseObject:%@", responseObject);
    } failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"errorerror:%@", error);
    }];
}
- (void)openURL{
   
//    [self.view addSubview:WEBVIEW];
    
    
    NSURL * URL = [NSURL URLWithString:Request_URL];
//    [[UIApplication sharedApplication] openURL:URL];
//    [WEBVIEW loadRequest:[NSURLRequest requestWithURL:URL]];
    NSURLRequest * request = [NSURLRequest requestWithURL:URL];
    
    
    NSOperationQueue *queue=[NSOperationQueue mainQueue];
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSData * dataaa = [NSData dataWithData:data];
        NSString *result = [[NSString alloc] initWithData:dataaa  encoding:NSUTF8StringEncoding];
        NSLog(@"22222222-------%@",result);

        
        if (data) {//请求成功
             NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                         NSLog(@"dictdictdictdict%@",dict);
            
                        //判断后，在界面提示登录信息
                         NSString *error=dict[@"error"];
                        if (error) {
//                              [MBProgressHUD showError:error];
                            NSLog(@"error::%@",error);
                             }else
                                 {
                                         NSString *success=dict[@"success"];
//                        25                 [MBProgressHUD showSuccess:success];
                                     NSLog(@"successsuccess------%@",success);
                                    }
                     }else   //请求失败
                         {
//                                 [MBProgressHUD showError:@"网络繁忙，请稍后重试！"];
                             NSLog(@"网络繁忙");
                             }
    }];
}





- (void)setupSearchView
{
   
    self.searchBar = [[UISearchBar alloc] init];
    
    self.navigationItem.titleView = self.searchBar;
    
//    //       //设置文本框左边的view
//    UITextField *textField = [[UITextField alloc]init];
//    textField.frame = CGRectMake(10, 30, 300, 30);
//    [self.view addSubview:textField];
//    textField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, 0)];
//    //设置显示模式为永远显示(默认不显示)
//    textField.leftViewMode = UITextFieldViewModeAlways;
//    
//    UITextField *searchBar=[[UITextField alloc]init];
//      //设置frmae
//         searchBar.width=300;
//    
//         searchBar.height=35;
//         //设置背景图片
//         searchBar.background=[UIImage resizedImage:@"searchbar_textfield_background"];
//     //    searchBar.textAlignment=NSTextAlignmentCenter;//说明：这是设置文字水平居中
//         //设置文字内容垂直居中
//         searchBar.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
//         //添加到导航栏中
//         self.navigationItem.titleView=searchBar;
    
  /*  self.searchBar = [[UISearchBar alloc] init];
    
    self.navigationItem.titleView = self.searchBar;

    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(searchBarDidCancel)];
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.searchBar.delegate = self;
   */
}



//设置 上面的 UPScrollView视图
- (void)setupScorllView
{

    
    CGFloat width = self.view.frame.size.width;
    CGFloat height = self.view.frame.size.height;
    //1.scrollView（有两件事）
    //    2.图片（代码增加到scrollView）
    for (int i = 1; i < ImageCount + 1; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        CGFloat imageX = (i - 1) * width;
        CGFloat imageY = 0.f;
        imageView.frame = CGRectMake(imageX, imageY, width, height);
        
        
#warning 要动态的添加5张图片到upScrollView上面去
        imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%02d", i]];
        [self.UpScrollView addSubview:imageView];
    }
    
    self.UpScrollView.contentSize = CGSizeMake(ImageCount * width, 0);
//   self.UpScrollView.contentOffset = CGSizeMake(0, 0)
    // 拖动分页
    self.UpScrollView.pagingEnabled = YES;
    //    设置代理
    self.UpScrollView.delegate = self;
    //  设置总页数
    self.pageControel.numberOfPages = ImageCount;

    
    
}

#pragma  mark scrollView delegate

//// scrollView滚动时执行
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    //    NSLog(@"scrollViewDidScroll");
//    }
//



/**
 *  向推荐商品 里面添加子控件
 */
- (void)addSubViewToScrollView
{
    // 每个控件里面width = （屏幕的宽 - 总间距）* 0.5;
    CGFloat width = (self.view.bounds.size.width - (kTuijianCol+1) * kTuiJianMargin) * 0.5;
    // 每个控件的height = width * 0.8
    CGFloat height = width * 0.8;
    int count = (int)self.dataList.count;
    // 记录一下最大的Y 值
    CGFloat scrollViewMaxY = 0.0;
    for (int i= 0; i < count; i++) {
        int col = i % 2;
        int row = i / 2;
        CGFloat viewX = kTuiJianMargin + col * (kTuiJianMargin + width);
        CGFloat viewY = kTuiJianMargin + row * (kTuiJianMargin + height);
        
        TuijianView *View = [[TuijianView alloc] init];
        View.delegate = self;
        View.model = self.dataList[i];
        View.backgroundColor = [UIColor whiteColor];
        View.frame = CGRectMake(viewX, viewY, width, height);
        [self.scrollView addSubview:View];
        
        if (i == (count -1)) scrollViewMaxY = CGRectGetMaxY(View.frame);
    }
    // 设置滚动范围
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width, scrollViewMaxY-60);
    self.scrollView.delegate = self;
//    self.scrollView.bounces = NO ;
    
    
}
/**
    积分按钮的点击事件（前面5个按钮，积分格式XXXX-XXXX）
 */
- (IBAction)btnDidClick:(UIButton *)sender {
    [self.searchBar resignFirstResponder];
    NSString *btnTitle = sender.currentTitle;
    // 去掉后面“积分”的两个字
    NSRange index = [btnTitle rangeOfString:@"积分"];
    NSString *strCount = [btnTitle substringToIndex:index.location];
    // 以积分格式的“-”为分割符截取出来
    NSArray *array = [strCount componentsSeparatedByString:@"-"];
    WebViewController *vc= [[WebViewController alloc] init];
    vc.title = @"积分查询商品";
    vc.searchFristCount = array[0];
    vc.searchTwoCount  = array[1];
    [self.navigationController pushViewController:vc animated:YES];
}
// 最后一个积分按钮 和最前面的一个按钮的点击事件(积分格式”XXXX以上“)
- (IBAction)LastestBtnDidClick:(UIButton *)sender {
    [self.searchBar resignFirstResponder];
    // 1. tag == 123 是20分以下按钮
    NSString *strCount;
    if(sender.tag == 123){
        NSRange index = [sender.currentTitle rangeOfString:@"分"];
        strCount = [sender.currentTitle substringToIndex:index.location];
    }else{
        NSRange index = [sender.currentTitle rangeOfString:@"以上"];
        strCount = [sender.currentTitle substringToIndex:index.location];
    }
    WebViewController *vc= [[WebViewController alloc] init];
    vc.title = @"积分查询商品";
    vc.searchFristCount = strCount;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - TuijianViewDelegate 推荐商品控件代理，传值
- (void)tuijianViewWithModel:(TuijianModel *)model
{
    NSLog(@"tuiJianView %@", model.title);
    [self.searchBar resignFirstResponder];
    WebViewController *vc= [[WebViewController alloc] init];
    vc.title = @"推荐商品";
    vc.searchFristCount = model.title;
    vc.searchTwoCount = model.buyCount;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length > 0) {
        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchBarDidClick)];
        self.navigationItem.rightBarButtonItem = rightBtn;
    }else {
        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(searchBarDidCancel)];
        self.navigationItem.rightBarButtonItem = rightBtn;
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self searchBarDidClick];
}
// 搜索框点击搜索时调用
- (void)searchBarDidClick
{
    [self.searchBar resignFirstResponder];
    WebViewController *vc= [[WebViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
// 搜索框点击取消时调用
- (void)searchBarDidCancel
{
    [self.searchBar resignFirstResponder];
}
// 点击屏幕让键盘退下
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.searchBar resignFirstResponder];
}
// 点击屏幕让键盘退下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.searchBar resignFirstResponder];
    CGPoint offset = self.UpScrollView.contentOffset;
    CGFloat offsetX = offset.x;
    CGFloat width = self.scrollView.frame.size.width;
    int pageNum = (offsetX + .5f *  width) / width;
    
    self.pageControel.currentPage = pageNum;

}
@end
